<template>
  <div class="update-touxiang">
    <img :src="img" class="img" ref="img"/>
    <div class="toolabr">
      <span @click="$emit('colse')">取消</span>
      <span @click="confirm">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserphoto } from '@/api/user'
export default {
  name: 'UpdateTouxiang',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  },
  methods: {
    confirm () {
      this.cropper.getCroppedCanvas().toBlob(blob => {
        // console.log(blob)
        this.updataphoto(blob)
      })
    },
    async updataphoto (blob) {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserphoto(formData)
        // 关闭弹层
        this.$emit('colse')
        // 更新视图
        this.$emit('updata-photo', data.data.photo)
        this.$toast.success('更新成功')
      } catch (err) {
        this.$toast('操作失败，请重试')
      }
    }
  }
}

</script>

<style scoped lang="less">
.update-touxiang {
  background-color: #000;
  width: 100%;
  height: 100%;
  .toolabr {
    position: fixed;
    bottom: 10px;
    width: 100%;
    color: #fff;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
